const express = require("express");
const expressWebSocket = require("express-ws");
var ffmpeg = require("fluent-ffmpeg");
// 本地 ffmpeg 路径下载 :https://www.gyan.dev/ffmpeg/builds/
ffmpeg.setFfmpegPath("D:/ssh-project/ssh-project/ffmpeg-7.1.1-essentials_build/bin/ffmpeg");
const webSocketStream = require("websocket-stream/stream");
const path = require("path");

const app = express();
app.use(express.static(__dirname));
expressWebSocket(app, null, {
  perMessgaeDeflate: true
});

app.ws("/rtsp/:id", rtspRequestHandle);
app.listen(8888);
console.log("Project is running at http://localhost:8888/");

app.use(express.static('public'))

app.set('views', path.join(__dirname, 'views'));
app.engine('.html', require('ejs').__express);
app.set('view engine', 'html')

app.get("/", (req, res) => {
  res.type("html");
  res.render("index", {});
});

function rtspRequestHandle(ws, req) {
  console.log("rtsp request handle");
  const stream = webSocketStream(ws, {
    binary: true,
    browserBufferTimeout: 1000000
  }, {
    browserBufferTimeout: 1000000
  });

  let url = req.query.url;
  console.log(`rtsp url: "${url}"`);
  console.log("rtsp params:", req.params);

  try {
    ffmpeg(url)
      .addInputOption("-rtsp_transport", "tcp", "-buffer_size", "102400")
      .on("start", () => {
        console.log(`"${url}" stream started.`)
      })
      .on("codecData", () => {
        console.log(`"${url}" stream codecData.`);
      })
      .on("error", err => {
        console.log(`"${url}" An Error occured: ${err.message}`);
      })
      .on("end", () => {
        console.log(`"${url}" stream end.`);
      })
      .outputFormat("flv").videoCodec("copy").noAudio().pipe(stream);
  } catch (error) {
    console.log(error);
  }
}